import React, { Component } from "react";
import DataSource from "../data/DataSource";

class CommentListWithNoHOC extends Component {
    constructor(props) {
        super(props)
        this.state = { comments: DataSource.getComments() }
    }

    componentDidMount() {
        DataSource.addOnCommentChangeListener(() => this.handleOnChange())
    }

    componentWillUnmount() {
        DataSource.removeOnCommentChangeListener(() => this.handleOnChange())
    }

    handleOnChange() {
        console.log("handle changed=======")
        this.setState({ comments: DataSource.getComments() })
    }

    render() {
        return <React.Fragment key={"hello"}>
            <button onClick={() => DataSource.changeComments()}>change comment</button>
            {this.state.comments.map((comment) => <Comment key={comment.id} comment={comment} />)}
        </React.Fragment>
    }
}


class CommentListEx extends Component {
    constructor(props) {
        super(props)
    }

    render() {
        return <React.Fragment key={"hello"}>
            <h2>=============HOC============</h2>
            <button onClick={()=>this.props.changeComments()}>ChangeComments</button>
            {this.props.data.map((comment) => <Comment key={comment.id} comment={comment} />)}
        </React.Fragment>
    }
}

function Comment(props) {
    return <div>
        <span>{props.comment.id}</span>
        <p>{props.comment.comment}</p>
    </div>
}

// const CommentListWithHOC = withSubscription(CommentList,(DataSource,props)=>DataSource.getComments())
function withSubscriptionComponent(WrappedComponent, selectData) {

    return class extends React.Component {
        constructor(props) {
            super(props)
            this.state = { data: selectData(DataSource, props) }
        }

        componentDidMount() {
            DataSource.addOnCommentChangeListener(() => this.handleOnChange())
        }

        componentWillUnmount() {
            DataSource.removeOnCommentChangeListener(() => this.handleOnChange())
        }

        handleOnChange() {
            this.setState({ data: selectData(DataSource, this.props) })
        }

        render() {
            return <WrappedComponent data={this.state.data} {...this.props} />
        }
    }
}

const CommentListWithHOC = withSubscriptionComponent(CommentListEx, (DataSource, props) => DataSource.getComments())
export default class HigherOrderComponents extends React.Component {
    render() {
        return <React.Fragment>
            <CommentListWithNoHOC />
            {/*props传递数据和操作，这里是改变评论列表 */}
            <CommentListWithHOC changeComments={()=>DataSource.changeComments()}/>
        </React.Fragment>
    }
}